/**
 * Read a file into the plugin
 */
function Read(file)
{
    var ioService=Components.classes["@mozilla.org/network/io-service;1"]
        .getService(Components.interfaces.nsIIOService);
    var scriptableStream=Components
        .classes["@mozilla.org/scriptableinputstream;1"]
        .getService(Components.interfaces.nsIScriptableInputStream);

    var channel=ioService.newChannel(file,null,null);
    var input=channel.open();
    scriptableStream.init(input);
    var str=scriptableStream.read(input.available());
    scriptableStream.close();
    input.close();
    return str;
}

/**
 * Do things after the content of website/page is loaded
 */
gBrowser.addEventListener("DOMContentLoaded", function(e) {
    var documentElement = e.originalTarget.defaultView.document;
	
	// Load css
	var head = documentElement.getElementsByTagName('head')[0],
		style = documentElement.createElement('style'),
		rules = documentElement.createTextNode(Read('chrome://woordenschat/skin/overlay.css'));

	style.type = 'text/css';
	if(style.styleSheet)
		style.styleSheet.cssText = rules.nodeValue;
	else style.appendChild(rules);
	head.appendChild(style);
});

/**
 * Main controller
 */
var Woordenschat = {
	/**
	 * Site to interact with
	 */
	url: 'http://127.0.0.1/woordenschat/',
	
	/**
	 * Loads 'Woordenschat'
	 */
	load: function() {
		if(Woordenschat.getSelection() == ''){
			return;
		}
		// Maincontainer
		var maindiv = content.document.createElement("div");
		maindiv.id = 'piraat';
		maindiv.innerHTML = '';
		var panel = content.document.createElement("div");
		panel.id = 'piraat-panel';
		maindiv.appendChild(panel);
		content.document.body.appendChild(maindiv);
		
		// next button
		var maindiv = content.document.getElementById('piraat');
		var next = content.document.createElement('button');
			//next.innerHTML = "Volgende";
			next.onclick = pagination.nextPage;
			next.id = 'piraat-nextButton';
			maindiv.appendChild(next);
		
		// exit button
		var exit = content.document.createElement('button');
			exit.onmouseup = Woordenschat.destroy;
			exit.id = 'piraat-exitButton';
			maindiv.appendChild(exit);
		
		content.document.getElementById('piraat').style.display = "block";
		//Woordenschat.getSelection();
		pagination.pages[0].begin();
		pagination.pageInfo();
	},
	
	/**
	 * Gets the word that has been selected.
	 * @return String word	Returns a string of the word that has been selected
	 */
	getSelection: function() {
		var word = '';
		word = content.window.getSelection().toString();
		Woordenschat.word = word;
		return word;
	},
	
	/**
	 * Reset everything of 'Woordenschat'
	 */
	destroy: function(){
		pagination.currentPage = 0;
		drawing.clearArea();
		var maindiv = content.document.getElementById('piraat');
		maindiv.parentNode.removeChild(maindiv);
	}
};